<!-- 发现 -->
<template>
	<view class="">
		<view class="u-page">
			<!-- 发现 -->
			<Home ref="home" v-if="current == 0" @goMore="goMore" />
			<!-- 商机 -->
			<Opportunity v-if="current == 1" />
			<!-- 消息 -->
			<Msg v-if="current ==2" />
			<!-- 我的 -->
			<Center v-if="current == 3" />
		</view>
		<!-- 与包裹页面所有内容的元素u-page同级，且在它的下方 -->
		<!-- <u-tabbar v-model="current" :list="list" @change="changeTab"></u-tabbar> -->

		<!-- <view class="" style="position: fixed;width: 100%;background: #fff;">
			<view class="" v-for="(v,i) in list" :key="i">
				{{v.text}}
				<text>{{v.}}</text>
				
			</view>
		</view> -->


		<view :class="isIPX ? 'chatRoom_tab_X-box' : 'chatRoom_tab-box'" class="flex-bettwen" style="z-index: 999;">
			<!-- <view class="center flex1" @tap="changeTab(0)">
				<u-icon :name="current == 0?'home':'home-fill'" size="38"
					:color="current==0?'#1296db':'#999999'"></u-icon>
				<view class="fs24" :style="current==0?'color: #1296db;':'color:#999999'">发现</view>
			</view> -->
			<view class="center flex1 " @tap="changeTab(0)">
				
				<u-icon :name="current == 0?'home':'home-fill'" size="38"
					:color="current==0?'#1296db':'#999999'"></u-icon>
				<view class="fs24" :style="current==0?'color: #1296db;':'color:#999999'">发现</view>
			</view>
			<view class="center flex1 " @tap="changeTab(1)">
				
				<u-icon :name="current == 1?'red-packet':'red-packet-fill'" size="38"
					:color="current==1?'#1296db':'#999999'"></u-icon>
				<view class="fs24" :style="current==1?'color: #1296db;':'color:#999999'">商机</view>
			</view>
			<view class="center flex1 position-r" @click="changeTab(2)">
				<view class="position-a tags" v-if="unReadSpotNum > 0 || unReadSpotNum == '99+'">
					{{ unReadSpotNum == '99+' ? unReadSpotNum : unReadSpotNum + unReadTotalNotNum }}
				</view>
				<u-icon :name="current == 2?'chat':'chat-fill'" size="38"
					:color="current==2?'#1296db':'#999999'"></u-icon>
				<view class="fs24" :style="current==2?'color: #1296db;':'color:#999999'">消息</view>
			</view>

			<view class="center flex1" @tap="changeTab(3)">
				<u-icon :name="current == 3?'account':'account-fill'" size="38"
					:color="current==3?'#1296db':'#999999'"></u-icon>
				<view class="fs24" :style="current==3?'color: #1296db;':'color:#999999'">我的</view>
			</view>
		</view>

	</view>
</template>

<script>
	import Home from './components/Home.vue'
	import Msg from './components/conversation.vue'
	import Opportunity from './components/opportunity.vue'
	import Center from './components/center.vue'
	let WebIM = require("@/utils/WebIM")["default"];
	let disp = require("@/utils/broadcast");
	import imUtil from '@/utils/imUtil';
	export default {
		components: {
			Home,
			Msg,
			Opportunity,
			Center
		},
		data() {
			return {
				list: [{
						iconPath: "home",
						selectedIconPath: "home-fill",
						text: '发现',
						customIcon: false,
					},
					{
						iconPath: "red-packet",
						selectedIconPath: "red-packet-fill",
						text: '商机',
						customIcon: false,
					},

					{
						iconPath: "chat",
						selectedIconPath: "chat-fill",
						text: '消息',
						count: 0,
						customIcon: false,
					},
					{
						iconPath: "account",
						selectedIconPath: "account-fill",
						text: '我的',
						customIcon: false,
					},
				],
				current: 0,
				conversationsList: [],
				chatList: [],

				unReadSpotNum: 0,
				unReadTotalNotNum: 0,
				isIPX: false,
			}
		},
		onLoad(options) {
			let shopId = uni.getStorageSync('shopInfo').id

			// let imToken = uni.getStorageSync('imToken')
			// let imUserName = uni.getStorageSync('imUserName')
			// if (imToken && imUserName) {
			// 	imUtil.loginImBytoken(imUserName, imToken)
			// } else {
			// 	uni.navigateTo({
			// 		url: '/pages/login/index'
			// 	})
			// }


			if (!shopId) {
				uni.navigateTo({
					url: '/pages/login/index'
				})
			}

			//监听未读消息数
			disp.on("em.unreadspot", this.onChatPageUnreadspot);

			// this.calcUnReadSpot()
			console.log('当前未读消息', getApp().globalData.unReadMessageNum, getApp().globalData.saveFriendList.length);


			this.setData({
				unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ?
					"99+" : getApp().globalData.unReadMessageNum,
				messageNum: getApp().globalData.saveFriendList.length,
				unReadNoticeNum: getApp().globalData.saveGroupInvitedList.length,
				unReadTotalNotNum: getApp().globalData.saveFriendList.length +
					getApp().globalData.saveGroupInvitedList.length,
			});


			if (getApp().globalData.isIPX) {
				this.setData({
					isIPX: true,
				});
			}
			
			
			

		},
		onUnload() {},
		onShow() {
			// let imToken = uni.getStorageSync('imToken')
			// let imUserName = uni.getStorageSync('imUserName')
			// imUtil.loginImBytoken(imUserName, imToken)



			// this.getConversationsList()

			// let that = this
			// // 消息页面监听接收消息回调
			// WebIM.conn.listen({
			// 	onTextMessage(message) {
			// 		console.log("消息页面监听接收消息回调：", message);

			// 		setTimeout(() => {
			// 			that.getConversationsList()
			// 		}, 1000)
			// 	},
			// })


		},
		// onPullDownRefresh() {},
		// onShareAppMessage() {},
		// onReachBottom() {},
		methods: {
			// 去更多
			goMore(e){
				this.current = e
			},
			
			//该方法用以计算本地存储消息的未读总数。
			calcUnReadSpot(message) {
				let myName = uni.getStorageSync("myUsername");
				let pushObj = uni.getStorageSync("pushStorageData")
				let pushAry = pushObj[myName] || []
				uni.getStorageInfo({
					success: function(res) {
						let storageKeys = res.keys;
						let newChatMsgKeys = [];
						let historyChatMsgKeys = [];
						storageKeys.forEach((item) => {
							if (item.indexOf(myName) > -1 && item.indexOf("rendered_") == -1) {
								newChatMsgKeys.push(item);
							}
						});
						let count = newChatMsgKeys.reduce(function(result, curMember, idx) {
							let newName = curMember.split(myName)[0]
							let chatMsgs;
							chatMsgs = uni.getStorageSync(curMember) || [];
							//过滤消息来源与当前登录ID一致的消息，不计入总数中。
							chatMsgs = chatMsgs.filter((msg) => msg.yourname !== myName);
							if (pushAry.includes(newName)) return result
							return result + chatMsgs.length;
						}, 0);
						getApp().globalData.unReadMessageNum = count;
						disp.fire("em.unreadspot", message);
					},
				});
			},
			onChatPageUnreadspot(message) {
				this.getLocalConversationlist();
				let currentLoginUser = WebIM.conn.context.userId;
				let id = message && message.chatType === 'groupchat' ? message?.to : message?.from;
				let pushObj = uni.getStorageSync("pushStorageData");
				let pushAry = pushObj[currentLoginUser] || []
				this.setData({
					pushConfigData: pushAry,
				});
				// if (message && pushValue.includes(id)) return
				this.setData({
					unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ?
						"99+" : getApp().globalData.unReadMessageNum,
				});
			},
			// 包含陌生人版本
			getLocalConversationlist() {
				const myName = uni.getStorageSync("myUsername");
				const me = this;
				uni.getStorageInfo({
					success: function(res) {
						let storageKeys = res.keys;
						let newChatMsgKeys = [];
						let historyChatMsgKeys = [];
						let len = myName.length;
						storageKeys.forEach((item) => {
							if (item.slice(-len) == myName && item.indexOf("rendered_") == -1) {
								newChatMsgKeys.push(item);
							} else if (
								item.slice(-len) == myName &&
								item.indexOf("rendered_") > -1
							) {
								historyChatMsgKeys.push(item);
							} else if (item === "INFORM") {
								newChatMsgKeys.push(item);
							}
						});
						me.packageConversation(newChatMsgKeys, historyChatMsgKeys);
					},
				});
			},
			//组件会话列表方法
			packageConversation(newChatMsgKeys, historyChatMsgKeys) {
				const me = this;
				const myName = uni.getStorageSync("myUsername");
				let conversationList = [];
				let lastChatMsg; //最后一条消息
				for (let i = historyChatMsgKeys.length; i > 0, i--;) {
					let index = newChatMsgKeys.indexOf(historyChatMsgKeys[i].slice(9));
					if (index > -1) {
						let newChatMsgs = uni.getStorageSync(newChatMsgKeys[index]) || [];
						if (newChatMsgs.length) {
							lastChatMsg = newChatMsgs[newChatMsgs.length - 1];
							lastChatMsg.unReadCount = newChatMsgs.length;
							newChatMsgKeys.splice(index, 1);
						} else {
							let historyChatMsgs = uni.getStorageSync(historyChatMsgKeys[i]);
							if (historyChatMsgs.length) {
								lastChatMsg = historyChatMsgs[historyChatMsgs.length - 1];
							}
						}
					} else {
						let historyChatMsgs = uni.getStorageSync(historyChatMsgKeys[i]);
						if (historyChatMsgs.length) {
							lastChatMsg = historyChatMsgs[historyChatMsgs.length - 1];
						}
					}
					if (
						lastChatMsg &&
						(lastChatMsg.chatType == "groupchat" ||
							lastChatMsg.chatType == "chatRoom")
					) {
						lastChatMsg.groupName = me.groupName[lastChatMsg.info.to];
					}
					lastChatMsg && lastChatMsg.username != myName &&
						conversationList.push(lastChatMsg);
				}
				for (let i = newChatMsgKeys.length; i > 0, i--;) {
					let newChatMsgs = uni.getStorageSync(newChatMsgKeys[i]) || [];
					if (newChatMsgs.length) {
						lastChatMsg = newChatMsgs[newChatMsgs.length - 1];
						lastChatMsg.unReadCount = newChatMsgs.length;
						if (
							lastChatMsg.chatType == "groupchat" ||
							lastChatMsg.chatType == "chatRoom"
						) {
							lastChatMsg.groupName = me.groupName[lastChatMsg.info.to];
						}
						lastChatMsg.username != myName && conversationList.push(lastChatMsg);
					}
				}
				conversationList.sort((a, b) => {
					return b.time - a.time;
				});
				this.setData({
					conversationList: conversationList,
				});
			},
			changeTab(index) {
				this.current = index
			},

		},
	}
</script>
<style lang="scss" scoped>
	.chatRoom_tab-box {
		width: 100%;
		height: 102rpx;
		background-color: #fff;
		position: fixed;
		bottom: 0;
		right: 0;
		border-top: 1px solid rgba(173, 185, 193, 0.5);
		display: flex;
		justify-content: space-around;
	}

	.chatRoom_tab_X-box {
		width: 100%;
		height: 142rpx;
		background-color: #fff;
		position: fixed;
		bottom: 0;
		right: 0;
		border-top: 1px solid rgba(173, 185, 193, 0.5);
		display: flex;
		justify-content: space-around;
	}

	.tags {
		color: #fff;
		background: red;
		width: 30rpx;
		height: 30rpx;
		font-size: 20rpx;
		border-radius: 50%;
		right: 40rpx;
		top: 0rpx;
	}
</style>